<script setup>

import { common_get, baseurl, no_param_post } from '../api/common'
import { onMounted, ref } from 'vue'

const SPECIAL = "-1"
const mtypes = ref([])
const sel_mtype = ref(SPECIAL)


// 分页相关
const _loading = ref(false)
const _total = ref(0)
const tableDatas = ref([])
const _pagesize = [50, 100, 200, 500]
const selPagesize = ref(50)

// 查询相关
const music_name = ref(""); // 歌名
// const music_name1_auto = ref(""); // 歌名
const music_name2_input = ref(""); // 歌名
const isDisabelDroplist = ref(true) // 是否禁用下拉

// 查询所有的`mtype`
async function get_music_types() {
  // "" 是无效数据, 不处理
  const url = `${baseurl}/api/searcher/musictype/all`
  const music_types = await common_get(url)
  mtypes.value = music_types
}

// `music type` change
async function musicTypeChange(val) {
  sel_mtype.value = val
  await get_table_datas(1)
}

// 清除选择
async function cleanSelectedMtype() {
  sel_mtype.value = SPECIAL
  await get_table_datas(1)
}

// 向查询的结果数据中添加字段
function optTableDatas(dataArr) {
  dataArr.forEach(item => {
    if (item.first != '' && item.code1 != '' && item.first.includes("pan.baidu.com")) {
      item.link1 = `${item.first}&pwd=${item.code1}`
    } else {
      item.link1 = ""
    }
  });
}

// 查询数据
async function get_table_datas(page) {
  _loading.value = true
  const url = `${baseurl}/api/searcher/title_and_type/query/${page}/${selPagesize.value}/${sel_mtype.value}?title=${music_name.value}`
  const res = await common_get(url)
  _total.value = res.total
  const _datas = res.datas
  optTableDatas(_datas)
  tableDatas.value = _datas
  _loading.value = false
}

// 分页相关
async function handleSizeChange(pagesize) {
  // console.log(`pagesize: ${pagesize}`)
  // console.log(`selPagesize: ${selPagesize.value}`)
  await get_table_datas(1)
}

// 分页相关
async function handleCurrentChange(page) {
  await get_table_datas(page)
}

// 只查询`title`
async function queryAllTitles(str) {
  const url = `${baseurl}/api/searcher/alltitles/query/${str}`
  const res = await common_get(url)
  return res.datas
}

// 自动补全输入框 的查询函数
const querySearch = async (queryString, cb) => {
  // const results = queryString
  //   ? restaurants.value.filter(createFilter(queryString))
  //   : restaurants.value
  // cb(results)
  const res = await queryAllTitles(queryString)
  // console.log(res)
  cb(res)
}

// 自动补全输入框 的选择函数
const handleSelect = async (item) => {
  music_name.value = item.value
  // `autocomplete`已经选中唯一的值了, 此时应该重置`sel_mtype`
  sel_mtype.value = SPECIAL
  await get_table_datas(1)
}

// `input` 响应键盘的回车事件
async function handleKeyEnter() {
  // console.log("music_name1_auto: ", music_name1_auto.value)
  // console.log("music_name2_input: ", music_name2_input.value)
  music_name.value = music_name2_input.value
  await get_table_datas(1)
}

// 点击`clear`后重置``
function resetAfterClear() {
  music_name.value = ""
}

// 记录点击次数
async function logClickCount(id, click) {
  const datas = tableDatas.value
  const len = datas.length
  // 先更新后端
  const url = `${baseurl}/api/searcher/IncreaseClick/${id}`
  const res = await no_param_post(url)
  // console.log(res) // true
  // 再更新前端
  for (let i = 0; i < len; i++) {
    const item = datas[i]
    if (item.id == id) {
      click = !click ? 0 : click
      item.click = Number.parseInt(click) + 1
      break
    }
  }
}

// on mounted
onMounted(async () => {
  await get_music_types()
  await get_table_datas(1)
})

</script>

<template>

  <!-- v-model="radio2" -->
  <div class="flex justify-items-start items-start">

    <el-radio-group v-model="sel_mtype">
      <el-radio-button @change="musicTypeChange(item)"
        v-for="(item, index) of mtypes.filter(a=>a!='')" :key="index" :label="item" :value="item" 
      />
    </el-radio-group>

    <el-button class="ml-3" type="danger" plain @click="cleanSelectedMtype">清除选择</el-button>

  </div>

  <!-- 查询 -->
  <div class="my-2 flex flex-row space-x-2">
    <div>
      <el-checkbox v-model="isDisabelDroplist" label="禁用下拉" size="large" />
    </div>
    <div class="w-1/2">
      <el-autocomplete
        v-if="!isDisabelDroplist"
        v-model="music_name"
        :fetch-suggestions="querySearch"
        :trigger-on-focus="false"
        clearable
        @clear="resetAfterClear"
        placeholder="查询, 请输入"
        @select="handleSelect"
      />
      <el-input clearable
        v-if="isDisabelDroplist" 
        @keyup.enter="handleKeyEnter"
        @clear="resetAfterClear"
        v-model="music_name2_input" placeholder="查询, 请输入, 回车触发查询"
      />
    </div>    
  </div>
  
  <!-- 分页 -->
  <el-pagination background 
    class="mt-2"
    v-model:page-size="selPagesize"
    :page-sizes="_pagesize"
    layout="total, sizes, prev, pager, next" 
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  :total="_total" />

  <!-- 数据 data table -->
  <el-table class="mt-1"
    :data="tableDatas"
    :loading="_loading"
    element-loading-text="数据加载中，请稍候..."
    element-loading-spinner="el-icon-loading"
  style="width: 100%">
    <el-table-column type="expand">
      <template #default="props">
        <div class="ml-10">
          <p>{{ props.row.title }}</p>
          <p>
            <span class="mr-2.5">{{ props.row.origin }}</span><span>{{ props.row.musictype }}</span>
          </p>
          <p>
            <span class="mr-2.5">{{ props.row.first }}</span>,<span>{{ props.row.code1 }}</span>
          </p>
          <p>
            <span class="mr-2.5">{{ props.row.second }}</span>,<span>{{ props.row.code2 }}</span>
          </p>
        </div>
      </template>
    </el-table-column>
    <el-table-column type="index" width="50" />
    <el-table-column prop="origin" label="origin" width="160" />
    <el-table-column prop="musictype" label="类型" width="80" />
    <el-table-column label="链接1" width="100">
      <template #default="props">
        <a class="text-blue-600" target="_blank" @click="logClickCount(props.row.id, props.row.click)"
          v-if="props.row.link1 != ''" :href="props.row.link1" :title="props.row.link1">
          点击直达
        </a>
        <span v-else :title="props.row.first">未知</span>
      </template>
    </el-table-column>
    <el-table-column prop="code1" label="提取码1" width="80" />
    <el-table-column label="链接2" width="100">
      <template #default="props">
        <a class="text-blue-600" target="_blank" @click="logClickCount(props.row.id, props.row.click)"
          v-if="props.row.second.includes('https://')" :href="props.row.second" :title="props.row.second">
          点击跳转
        </a>
        <span v-else :title="props.row.second">未知</span>
      </template>
    </el-table-column>
    <el-table-column prop="code2" label="提取码2" width="80" />
    <el-table-column prop="click" label="点击数" width="80" />
    <el-table-column prop="title" label="歌名" />
  </el-table>

  <!-- 回到顶部 -->
  <el-backtop :right="100" :bottom="100" />

</template>

<style scoped>
</style>